import { FC, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import WebView, { WebViewNavigation } from 'react-native-webview'
import { StackProps } from '@/routes/type'
import { Pressable, StyleSheet, Text, View } from 'react-native'
import { PanGestureHandler } from 'react-native-gesture-handler'
import { LinearGradient } from 'expo-linear-gradient'
import useGetStatusBar from '@/utils/useGetStatusBar'
import { common } from '@/assets/style/common'
import { useStore } from '@/store'
const onceNavigation = (navigation: any) => {
  let once = false
  return () => {
    !once && (once = true) && navigation.goBack()
  }
}
const MyWebView: FC<StackProps<'MyWebView'>> = ({ navigation, route }) => {
  const { variableStore } = useStore()
  const webRef = useRef<WebView>(null)
  const [canGoBack, setCanGoBack] = useState(false)
  const [barHeight] = useGetStatusBar()
  const uri = useMemo(
    () => route.params.url || variableStore.ipAddress + ':6500',
    [route.params.url],
  )
  const goBackOnce = useCallback(onceNavigation(navigation), [])
  useEffect(() => {
    navigation.setOptions({
      gestureEnabled: !canGoBack,
    })
  }, [canGoBack])
  function goBack() {
    if (canGoBack) {
      webRef.current?.goBack()
    } else {
      goBackOnce()
    }
  }
  function handleGesture({ nativeEvent }: any) {
    if (nativeEvent.translationX > 50) {
      goBack()
      return false
    }
    return false
  }
  function handleNavigationStateChange(state: WebViewNavigation) {
    setCanGoBack(state.canGoBack)
  }
  return (
    <PanGestureHandler
      onGestureEvent={handleGesture}
      hitSlop={{ left: 30 }}
      activeOffsetX={[-10, 10]}
    >
      <View style={[common.flexCol, style.contain]}>
        <LinearGradient
          start={{ x: 0.2, y: 0.3 }}
          end={{ x: 0.8, y: 0.7 }}
          colors={['#73d7f7', '#57aef0']}
          style={[
            style.header,
            {
              paddingTop: barHeight,
            },
          ]}
        >
          <Pressable onPress={goBack}>
            <Text style={style.backIcon}>&#xe601;</Text>
          </Pressable>
        </LinearGradient>
        <View style={style.webview}>
          <WebView
            allowsBackForwardNavigationGestures
            ref={webRef}
            onNavigationStateChange={handleNavigationStateChange}
            source={{ uri }}
          />
        </View>
      </View>
    </PanGestureHandler>
  )
}
export default MyWebView
const style = StyleSheet.create({
  header: {
    width: '100%',
    display: 'flex',
    paddingHorizontal: 12,
    paddingBottom: 12,
  },
  backIcon: {
    color: '#fff',
    fontSize: 24,
    fontFamily: 'iconfont',
  },
  contain: {
    width: '100%',
    height: '100%',
    flexDirection: 'column',
  },
  webview: {
    flexGrow: 1,
    width: '100%',
  },
})
